package com.marvin.demo.service;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author marvin
 * 生成 Token 的工具类
 */
public class TokenUtils {

    private static final String secret = "123456";

    public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60;

    public static String createToken(Long userId) {
        Map<String, Object> claims = new HashMap<>();
        Map<String, Object> header = new HashMap<>();
        claims.put("moderator", true);
        claims.put("aud", "jitsi");
        claims.put("iss", "smartdean");
        claims.put("sub", "*");
        claims.put("room", "*");
        claims.put("exp", 1672502400);

        //指定header
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, secret)
                .setClaims(claims)
                .setSubject("*")
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setHeader(header)
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000));
        String token = jwtBuilder.compact();
        return token;
    }

    // TODO
    public static Map<String, Object> checkToken(String token) {
        try {
            Jwt parse = Jwts.parser().setSigningKey(secret).parse(token);
            return (Map<String, Object>) parse.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Long id = 1L;
        String tk = createToken(id);
        System.out.println(tk);
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJqaXRzaSIsInN1YiI6IioiLCJtb2RlcmF0b3IiOnRydWUsImlzcyI6InNtYXJ0ZGVhbiIsImV4cCI6MTY2MzE0OTQzNSwiaWF0IjoxNjYzMTMxNDM1LCJyb29tIjoiKiJ9.1qydZhyIBAhDx8hrgG_WcQ8w52MDlPQGSwFee_S-7ok";
        Map<String, Object> map = checkToken(token);
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            System.out.print(key);
            System.out.print("----");
            System.out.println(value);
        }
    }

}
